package cn.edu.qzuie.artist.module.td.service.workscatagory;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.edu.qzuie.artist.module.td.controller.admin.workscatagory.vo.*;
import cn.edu.qzuie.artist.module.td.dal.dataobject.workscatagory.WorksCatagoryDO;
import cn.edu.qzuie.artist.framework.common.util.object.BeanUtils;

import cn.edu.qzuie.artist.module.td.dal.mysql.workscatagory.WorksCatagoryMapper;

import static cn.edu.qzuie.artist.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.edu.qzuie.artist.module.td.enums.ErrorCodeConstants.*;

/**
 * 作品分类 Service 实现类
 *
 * @author 泉信管理员
 */
@Service
@Validated
public class WorksCatagoryServiceImpl extends ServiceImpl<WorksCatagoryMapper,WorksCatagoryDO> implements WorksCatagoryService {

    @Resource
    private WorksCatagoryMapper worksCatagoryMapper;

    @Override
    public Long createWorksCatagory(WorksCategorySaveReqVO createReqVO) {
        // 校验父编号的有效性
        validateParentWorksCatagory(null, createReqVO.getParentId());
        // 校验分类名称的唯一性
        validateWorksCatagoryCatagoryNameUnique(null, createReqVO.getParentId(), createReqVO.getCategoryName());

        // 插入
        WorksCatagoryDO worksCatagory = BeanUtils.toBean(createReqVO, WorksCatagoryDO.class);
        worksCatagoryMapper.insert(worksCatagory);
        // 返回
        return worksCatagory.getId();
    }

    @Override
    public void updateWorksCatagory(WorksCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateWorksCatagoryExists(updateReqVO.getId());
        // 校验父编号的有效性
        validateParentWorksCatagory(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验分类名称的唯一性
        validateWorksCatagoryCatagoryNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getCategoryName());

        // 更新
        WorksCatagoryDO updateObj = BeanUtils.toBean(updateReqVO, WorksCatagoryDO.class);
        worksCatagoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorksCatagory(Long id) {
        // 校验存在
        validateWorksCatagoryExists(id);
        // 校验是否有子作品分类
        if (worksCatagoryMapper.selectCountByPid(id) > 0) {
            throw exception(WORKS_CATAGORY_EXITS_CHILDREN);
        }
        // 删除
        worksCatagoryMapper.deleteById(id);
    }

    private void validateWorksCatagoryExists(Long id) {
        if (worksCatagoryMapper.selectById(id) == null) {
            throw exception(WORKS_CATAGORY_NOT_EXISTS);
        }
    }

    private void validateParentWorksCatagory(Long id, Long pid) {
        if (pid == null || WorksCatagoryDO.PID_ROOT.equals(pid)) {
            return;
        }
        // 1. 不能设置自己为父作品分类
        if (Objects.equals(id, pid)) {
            throw exception(WORKS_CATAGORY_PARENT_ERROR);
        }
        // 2. 父作品分类不存在
        WorksCatagoryDO parentWorksCatagory = worksCatagoryMapper.selectById(pid);
        if (parentWorksCatagory == null) {
            throw exception(WORKS_CATAGORY_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父作品分类，如果父作品分类是自己的子作品分类，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            pid = parentWorksCatagory.getParentId();
            if (Objects.equals(id, pid)) {
                throw exception(WORKS_CATAGORY_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父作品分类
            if (pid == null || WorksCatagoryDO.PID_ROOT.equals(pid)) {
                break;
            }
            parentWorksCatagory = worksCatagoryMapper.selectById(pid);
            if (parentWorksCatagory == null) {
                break;
            }
        }
    }

    private void validateWorksCatagoryCatagoryNameUnique(Long id, Long pid, String catagoryName) {
        WorksCatagoryDO worksCatagory = worksCatagoryMapper.selectByPidAndCatagoryName(pid, catagoryName);
        if (worksCatagory == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的作品分类
        if (id == null) {
            throw exception(WORKS_CATAGORY_CATAGORY_NAME_DUPLICATE);
        }
        if (!Objects.equals(worksCatagory.getId(), id)) {
            throw exception(WORKS_CATAGORY_CATAGORY_NAME_DUPLICATE);
        }
    }

    @Override
    public WorksCatagoryDO getWorksCatagory(Long id) {
        return worksCatagoryMapper.selectById(id);
    }

    @Override
    public List<WorksCatagoryDO> getWorksCatagoryList(WorksCategoryListReqVO listReqVO) {
        return worksCatagoryMapper.selectList(listReqVO);
    }

    @Override
    public List<WorksCatagoryDO> getWorksCatagoryDO() {
          return worksCatagoryMapper.selectList();
    }

}